<template>
  <view class="ai-chat-container">
    <!-- 聊天记录区域 -->
    <div ref="chatContainer" class="chat-messages" @scroll="handleScroll">
      <view
        v-for="(message, index) in messages"
        :key="index"
        :class="[
          'message',
          message.type === 'ai' ? 'ai-message' : 'user-message',
        ]"
      >
        <view class="content">
          <view
            v-if="message.type === 'ai' && message.isThinking"
            class="thinking"
          >
            <view class="dot"></view>
            <view class="dot"></view>
            <view class="dot"></view>
          </view>
          <view v-else class="text">
            <view
              v-if="message.type === 'ai'"
              v-html="formatMarkdown(message.content)"
              class="markdown-content"
            ></view>
            <text v-else>{{ message.content }}</text>
          </view>
        </view>
      </view>
    </div>

    <!-- 输入区域 -->
    <view class="input-area">
      <textarea
        v-model="userInput"
        placeholder="请输入您的问题..."
        :disabled="isLoading"
        :cursor-spacing="20"
        :show-confirm-bar="false"
        :adjust-position="false"
        @confirm="sendMessage"
      ></textarea>
      <button class="send-btn" @tap="sendMessage" :disabled="isLoading">
        发送
      </button>
    </view>
  </view>
</template>
  
<script>
export default {
  data() {
    return {
      messages: [],
      userInput: '',
      isLoading: false,
      sessionId: '',
      isAutoScrollEnabled: true,
    }
  },

  onLoad() {
    // 生成会话ID
    this.sessionId = this.generateUUID()
    // 显示欢迎语
    this.showAIWelcome()
  },

  methods: {
    // 生成UUID
    generateUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
        /[xy]/g,
        function (c) {
          const r = (Math.random() * 16) | 0
          const v = c === 'x' ? r : (r & 0x3) | 0x8
          return v.toString(16)
        }
      )
    },

    // 显示AI欢迎语
    showAIWelcome() {
      this.messages.push({
        type: 'ai',
        content: '我是您的智能助手，请问有什么可以帮您？',
        isThinking: false,
      })
    },

    // 显示思考动画
    showThinking() {
      this.messages.push({
        type: 'ai',
        content: '',
        isThinking: true,
      })
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    // 流式输出处理
    async streamResponse(message) {
      const aiMessage = this.messages[this.messages.length - 1]
      aiMessage.content = ''

      try {
        const url = `/zgrsqfwai/api/chatFlux?userId=${encodeURIComponent(
          this.sessionId
        )}&message=${encodeURIComponent(message)}`

        return new Promise((resolve, reject) => {
          const eventSource = new EventSource(url)

          eventSource.onmessage = (event) => {
            if (event.data === '[DONE]') {
              eventSource.close()
              // 确保最后一次内容更新后滚动到底部
              this.scrollToBottom()
              resolve()
              return
            }

            try {
              const data = JSON.parse(event.data)
              if (data.type === 'ai_response') {
                if (aiMessage.isThinking) {
                  aiMessage.isThinking = false
                }
                aiMessage.content += data.content

                // 直接滚动到底部，不使用防抖
                this.scrollToBottom()
              }
            } catch (e) {
              console.error('Parse message error:', e)
            }
          }

          eventSource.onerror = (error) => {
            console.error('EventSource error:', error)
            eventSource.close()
            if (!aiMessage.content) {
              aiMessage.isThinking = false
              aiMessage.content = '抱歉，我现在有点小问题，请稍后再试～'
            }
            reject(error)
          }
        })
      } catch (error) {
        console.error('Stream error:', error)
        throw error
      }
    },

    // 发送消息
    async sendMessage() {
      if (!this.userInput.trim() || this.isLoading) return

      // 添加用户消息
      this.messages.push({
        type: 'user',
        content: this.userInput,
      })

      // 清空输入框并保存消息
      const userMessage = this.userInput
      this.userInput = ''

      // 显示AI思考动画
      this.showThinking()
      this.isLoading = true

      try {
        await this.streamResponse(userMessage)
      } catch (error) {
        console.error('Error:', error)
      } finally {
        this.isLoading = false
      }
    },

    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        try {
          const container = this.$refs.chatContainer
          if (container) {
            // 直接设置 scrollTop 属性，不使用 setTimeout
            container.scrollTop = container.scrollHeight
          }
        } catch (error) {
          console.error('Scroll error:', error)
        }
      })
    },

    // 添加滚动事件处理
    handleScroll() {
      // 移动端不需要这个逻辑，总是自动滚动
      this.isAutoScrollEnabled = true
    },

    // 加载更多历史消息
    loadMore() {
      // 实现加载更多历史消息的逻辑
    },

    // 添加 Markdown 格式化方法
    formatMarkdown(content) {
      if (!content) return ''

      // 处理所有级别的标题
      content = content.replace(
        /^(#{1,6}) \*\*(.*?)\*\*/gm,
        (match, hashes, title) => {
          const level = hashes.length
          return `<h${level}>${title}</h${level}>`
        }
      )

      // 处理粗体
      content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')

      // 处理分隔线
      content = content.replace(/^---$/gm, '<hr>')

      // 处理列表
      content = content.replace(/^- (.*?)$/gm, '<li>$1</li>')
      content = content.replace(/(<li>.*?<\/li>\n?)+/g, '<ul>$&</ul>')

      // 处理换行
      content = content.replace(/\n/g, '<br>')

      return content
    },
  },
}
</script>
  
<style lang="scss" scoped>
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.chat-messages {
  flex: 1;
  padding: 20rpx;
  box-sizing: border-box;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  height: 100%; // 确保容器有高度
}

.message {
  display: flex;
  margin-bottom: 30rpx;
  user-select: text;

  &.ai-message {
    .content {
      margin-left: 0;
      background-color: #ffffff;
    }
  }

  &.user-message {
    flex-direction: row-reverse;

    .content {
      margin-right: 0;
      background-color: #66c2ff;
      color: #fff;
    }
  }
}

.content {
  max-width: 70%;
  padding: 20rpx;
  border-radius: 10rpx;
  word-break: break-all;
}

.thinking {
  display: flex;
  align-items: center;
  padding: 10rpx 0;

  .dot {
    width: 12rpx;
    height: 12rpx;
    margin: 0 6rpx;
    background-color: #999;
    border-radius: 50%;
    animation: thinking 1.4s infinite ease-in-out;

    &:nth-child(2) {
      animation-delay: 0.2s;
    }

    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

.input-area {
  padding: 20rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  align-items: center;
  position: relative;
  z-index: 1;
}

textarea {
  flex: 1;
  height: 80rpx;
  min-height: 80rpx;
  max-height: 80rpx;
  padding: 10rpx 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  font-size: 28rpx;
  line-height: 40rpx;
}

.send-btn {
  width: 120rpx;
  height: 80rpx;
  margin-left: 20rpx;
  background-color: #66c2ff;
  color: #fff;
  border-radius: 10rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  word-break: keep-all;

  &:disabled {
    background-color: #ccc;
  }
}

@keyframes thinking {
  0%,
  80%,
  100% {
    transform: scale(0.6);
    opacity: 0.3;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.markdown-content {
  ::v-deep {
    img {
      display: block;
      width: 100% !important;
      height: auto !important;
      object-fit: cover !important;
    }
    h1 {
      font-size: 40rpx;
      font-weight: bold;
      margin: 24rpx 0;
      color: #333;
    }
    h2 {
      font-size: 36rpx;
      font-weight: bold;
      margin: 22rpx 0;
      color: #333;
    }
    h3 {
      font-size: 32rpx;
      font-weight: bold;
      margin: 20rpx 0;
      color: #333;
    }
    h4 {
      font-size: 30rpx;
      font-weight: bold;
      margin: 18rpx 0;
      color: #333;
    }
    h5 {
      font-size: 28rpx;
      font-weight: bold;
      margin: 16rpx 0;
      color: #333;
    }
    h6 {
      font-size: 26rpx;
      font-weight: bold;
      margin: 14rpx 0;
      color: #333;
    }
    strong {
      font-weight: bold;
    }
    hr {
      border: none;
      border-top: 1px solid #eee;
      margin: 20rpx 0;
    }
    ul {
      padding-left: 40rpx;
      margin: 10rpx 0;
    }
    li {
      margin: 10rpx 0;
      list-style-type: disc;
    }
    br {
      display: block;
      content: '';
      margin: 10rpx 0;
    }
    p {
      text-indent: 2em !important;
      color: #333;
      padding: 10rpx 0;
    }
  }
}
</style>